<template>
  <view class="set-page">
    <!-- 顶部导航 -->
    <view class="status-bar" :style="{ height: navHeight + 'px', 'padding-top': statusBarHeight + 'px' }">
      <view class="nav-bar">
        <view class="nav-bar-left">
          <image src="/static/left_arrow.png" class="nav-back-icon" @click="goBack" />
        </view>
        <view class="nav-bar-title">新的朋友</view>
        <view class="nav-bar-right"></view>
      </view>
    </view>
    <view class="status-height-color" :style="{ height: navHeight + 'px', 'padding-top': statusBarHeight + 'px' }">
    </view>

    <!-- 好友列表 -->
    <scroll-view class="main-scroll-view" scroll-y :scroll-with-animation="true" :enhanced="true" :bounces="true"
      :show-scrollbar="false" :style="{ height: scrollViewHeight }" @refresherrefresh="onRefresh"
      :refresher-enabled="true" :refresher-triggered="refreshing">
      <view class="friend-list-container">
        <view class="friend-list">
          <view class="friend-item" v-for="(friend, index) in filteredFriendList"
            :key="friend.id ? friend.id : 'index_' + index">
            <!-- 左侧头像 -->
            <view class="friend-avatar-wrapper">
              <view class="friend-avatar"
                :style="{ backgroundImage: `url(${getAvatarUrl(friend.avatar) || '/static/default_avatar.jpg'})` }"
                :class="{ 'loaded': friend.avatarLoaded }">
              </view>
              <!-- 隐藏的image标签用于监听加载事件 -->
              <image class="hidden-avatar-image" :src="getAvatarUrl(friend.avatar) || '/static/default_avatar.jpg'"
                @load="onAvatarLoad(index)" @error="onAvatarError(index)" />
              <!-- 加载动画 -->
              <view class="avatar-loading" v-if="!friend.avatarLoaded">
                <view class="avatar-loading-spinner"></view>
              </view>
              <!-- 骨架屏占位符 -->
              <view class="avatar-skeleton" v-if="!friend.avatarLoaded">
                <view class="avatar-skeleton-shimmer"></view>
              </view>
            </view>

            <!-- 中间内容区域 -->
            <view class="friend-content">
              <view class="friend-title-row">
                <text class="friend-name">{{ friend.name }}</text>
              </view>
              <text class="friend-desc">{{ friend.telephone }}</text>
            </view>

            <!-- 右侧操作按钮 -->
            <view class="friend-actions" v-if="friend.showmsg === '待操作'">
              <view class="action-btn reject-btn" @click.stop="onRejectFriend(friend)">
                <text class="action-text">拒绝</text>
              </view>
              <view class="action-btn accept-btn" @click.stop="onAcceptFriend(friend)">
                <text class="action-text">通过</text>
              </view>
            </view>
            <view class="friend-actions" v-else>
              <view class="action-btn reject-btn disabled">
                <text class="action-text">{{ friend.showmsg }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-more" v-if="friendLoading">
          <view class="loading-spinner"></view>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 无数据状态 -->
        <view class="empty-friend" v-if="!friendLoading && filteredFriendList.length === 0">
          <image class="empty-img" src="/static/empty_state.png" />
          <text class="empty-text">暂无新好友</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  name: 'MyFriend',
  data() {
    return {
      navHeight: "", //整体顶部导航栏的高度
      statusBarHeight: "", //状态栏高度
      scrollViewHeight: 0, // 滚动视图高度
      searchKeyword: "", // 搜索关键词
      friendLoading: false, // 好友加载状态
      friendList: [], // 好友申请列表，从接口获取
      refreshing: false // 下拉刷新状态
    }
  },
  computed: {
    filteredFriendList() {
      if (!this.searchKeyword) {
        return this.friendList;
      }
      const keyword = this.searchKeyword.toLowerCase();
      return this.friendList.filter(friend =>
        friend.name.toLowerCase().includes(keyword) ||
        friend.description.toLowerCase().includes(keyword)
      );
    }
  },
  onLoad() {
    let { statusBarHeight, system } = uni.getSystemInfoSync();
    this.statusBarHeight = statusBarHeight;
    this.navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);

    // 计算滚动视图高度
    this.calculateScrollViewHeight();

    // 加载新朋友申请列表
    this.loadNewFriendList();
  },
  onShow() {
    this.loadNewFriendList();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },

    // 搜索输入
    onSearchInput(e) {
      this.searchKeyword = e.detail.value;
    },

    // 清除搜索
    clearSearch() {
      this.searchKeyword = "";
    },

    // 头像加载成功
    onAvatarLoad(index) {
      console.log('头像加载成功:', index);
      if (this.friendList[index]) {
        this.$set(this.friendList[index], 'avatarLoaded', true);
      }
    },

    // 头像加载失败
    onAvatarError(index) {
      console.log('头像加载失败:', index);
      if (this.friendList[index]) {
        // 加载失败时使用默认头像
        this.$set(this.friendList[index], 'avatar', '/static/default_avatar.jpg');
        this.$set(this.friendList[index], 'avatarLoaded', true);
      }
    },

    // 获取头像URL
    getAvatarUrl(avatar) {
      if (!avatar) {
        return '/static/default_avatar.jpg';
      }
      // 如果已经是完整url，直接返回
      if (/^https?:\/\//.test(avatar)) return avatar;
      // 防止多斜杠
      return 'https://tob.cycyai.com/' + avatar.replace(/^\/+/, '');
    },

    // 拒绝好友请求
    onRejectFriend(friend) {
      uni.showModal({
        title: '确认拒绝',
        content: `确定要拒绝${friend.name}的好友请求吗？`,
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.handleFriendAction(friend, 'reject');
          }
        }
      });
    },

    // 通过好友请求
    onAcceptFriend(friend) {
      uni.showModal({
        title: '确认通过',
        content: `确定要通过${friend.name}的好友请求吗？`,
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.handleFriendAction(friend, 'accept');
          }
        }
      });
    },
    // 计算滚动视图高度
    calculateScrollViewHeight() {
      const { statusBarHeight, system } = uni.getSystemInfoSync();
      const navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
      this.scrollViewHeight = `calc(100vh - ${navHeight}px)`;
    },

    // 加载新朋友申请列表
    async loadNewFriendList() {
      try {
        this.friendLoading = true;

        // 获取用户信息
        let userInfo = uni.getStorageSync('userInfo');
        const userid = userInfo?.data?.userid || userInfo?.userid || '';

        if (!userid) {
          uni.showToast({
            title: '用户信息获取失败',
            icon: 'none'
          });
          return;
        }

        // 调用获取新朋友申请列表接口
        const response = await this.$Request.postApi('/bot/api/agentcgetuserfriendlist', {
          userid: userid
        });

        if (response.status === 1) {
          // 成功获取数据
          if (response.data && Array.isArray(response.data)) {
            // 处理接口返回的数据，转换为页面需要的格式
            this.friendList = response.data.map(item => {
              const userInfo = item.showUserInfo || {};
              const avatar = userInfo.user_head || '/static/default_avatar.jpg';
              return {
                id: item.id,
                name: userInfo.nickname || '未知用户',
                avatar: avatar,
                avatarLoaded: avatar === '/static/default_avatar.jpg', // 默认头像直接设置为已加载
                status: item.status,
                showmsg: item.showmsg,
                userid: item.userid,
                friendid: item.friendid,
                telephone: userInfo.telephone
              };
            });

            // 延迟检查头像加载状态，确保网络头像能够正确显示
            this.$nextTick(() => {
              this.checkAvatarLoadingStatus();
              // 调试信息
              this.debugAvatarInfo();
            });
          } else {
            this.friendList = [];
          }
        } else {
          // 获取失败
          uni.showToast({
            title: response.message || '获取好友申请列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取新朋友申请列表失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        this.friendLoading = false;
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.refreshing = true;
      try {
        await this.loadNewFriendList();
      } finally {
        this.refreshing = false;
      }
    },

    // 检查头像加载状态
    checkAvatarLoadingStatus() {
      // 延迟检查，确保DOM更新完成
      setTimeout(() => {
        this.friendList.forEach((friend, index) => {
          if (!friend.avatarLoaded && friend.avatar !== '/static/default_avatar.jpg') {
            // 如果头像还未加载且不是默认头像，尝试重新加载
            console.log('检查头像加载状态:', index, friend.avatar);
            // 强制触发头像重新加载
            this.$set(this.friendList[index], 'avatar', friend.avatar + '?t=' + Date.now());
          }
        });
      }, 100);
    },

    // 调试：打印头像信息
    debugAvatarInfo() {
      console.log('当前好友列表头像信息:');
      this.friendList.forEach((friend, index) => {
        console.log(`索引${index}:`, {
          name: friend.name,
          avatar: friend.avatar,
          avatarLoaded: friend.avatarLoaded,
          avatarUrl: this.getAvatarUrl(friend.avatar)
        });
      });
    },

    // 统一处理好友操作（拒绝/通过）
    async handleFriendAction(friend, action) {
      try {
        // 显示加载提示
        uni.showLoading({
          title: action === 'accept' ? '通过中...' : '拒绝中...'
        });

        // 调用新朋友申请列表是否通过操作接口
        console.log('调用好友操作接口参数:', {
          id: friend.id,
          status: action === 'accept' ? '1' : '2'
        });

        const response = await this.$Request.postApi('/bot/api/agentcsetuserfriendstatus', {
          id: friend.id,
          status: action === 'accept' ? '1' : '2' // 通过传1，拒绝传2
        });

        console.log('好友操作接口响应:', response);

        // 隐藏加载提示
        uni.hideLoading();

        if (response.status === 1) {
          // 操作成功
          if (action === 'accept') {
            uni.showToast({
              title: response.message || '已通过好友请求',
              icon: 'none'
            });
            // 更新好友状态为已添加
            const index = this.friendList.findIndex(item => item.id === friend.id);
            if (index > -1) {
              this.$set(this.friendList[index], 'showmsg', '已添加');
              this.$set(this.friendList[index], 'status', '1');
            }
          } else {
            uni.showToast({
              title: response.message || '已拒绝好友请求',
              icon: 'none'
            });
          }
        } else {
          // 操作失败
          uni.showToast({
            title: response.message || '操作失败',
            icon: 'none'
          });
        }

      } catch (error) {
        // 隐藏加载提示
        uni.hideLoading();
        console.error('好友操作失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.set-page {
  min-height: 100vh;
  background: #100D05;
  padding: 0 32rpx;
  color: #fff;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #100D05;
  display: flex;
  align-items: center;
  color: #fff;
  font-weight: 500;
  font-size: 35rpx;

  .nav-bar {
    display: flex;
    align-items: center;
    width: 100%;

    .nav-bar-left {
      display: flex;
      align-items: center;
      margin-left: 32rpx;

      .nav-back-icon {
        width: 46.15rpx;
        height: 46.15rpx;
      }
    }

    .nav-bar-title {
      flex: 1;
      text-align: center;
      font-size: 35rpx;
      font-weight: 500;
    }

    .nav-bar-right {
      width: 60rpx;
    }
  }
}

.status-height-color {
  background-color: #100D05;
}

// 搜索框
.search-container {
  // padding: 0 30rpx;
  margin-top: 20rpx;
  margin-bottom: 30rpx;

  .search-box {
    display: flex;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 40rpx;
    padding: 16rpx 30rpx;
    margin-bottom: 20rpx;

    .search-icon {
      width: 38rpx;
      height: 38rpx;
      margin-right: 20rpx;
    }

    .search-input {
      flex: 1;
      height: 48rpx;
      line-height: 48rpx;
      font-size: 28rpx;
      color: #fff;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5);
      }
    }

    .clear-icon {
      width: 29rpx;
      height: 29rpx;
      margin-left: 20rpx;
    }
  }
}

.new-friend-container {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
  padding-bottom: 16rpx;

  .new-friend-icon {
    width: 80rpx;
    height: 80rpx;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 30rpx;

    .new-friend-icon-img {
      width: 50rpx;
      height: 50rpx;
    }
  }

  .new-friend-title {
    font-size: 30rpx;
    font-weight: 600;
  }
}

// 主滚动视图
.main-scroll-view {
  width: 100%;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
  padding-top: 0;
  box-sizing: border-box;
}

// 好友列表容器
.friend-list-container {
  // padding: 0 30rpx;
  padding-bottom: 120rpx;
  min-height: 100%;
}

// 好友列表
.friend-list {
  -webkit-overflow-scrolling: touch;

  .friend-item {
    display: flex !important;
    align-items: center;
    padding: 20rpx 0;
    min-height: 84rpx;
    border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
    position: relative;

    &:last-child {
      border-bottom: none;
      margin-bottom: 40rpx;
    }

    // 头像包装器
    .friend-avatar-wrapper {
      position: relative;
      width: 84rpx;
      height: 84rpx;
      border-radius: 50%;
      margin-right: 30rpx;
      flex-shrink: 0;
      overflow: hidden;
      background-color: #2c2c2e;

      .friend-avatar {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        background-color: #2c2c2e;
        opacity: 1;
        transition: opacity 0.3s ease-in-out;

        &.loaded {
          opacity: 1;
        }
      }

      .hidden-avatar-image {
        position: absolute;
        top: -9999px;
        left: -9999px;
        width: 1px;
        height: 1px;
        opacity: 0;
        pointer-events: none;
      }

      // 加载动画
      .avatar-loading {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: transparent;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1;
        transition: opacity 0.3s ease-in-out;

        .avatar-loading-spinner {
          width: 40rpx;
          height: 40rpx;
          border: 3rpx solid rgba(0, 123, 255, 0.2);
          border-top: 3rpx solid #007bff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          box-shadow: 0 0 20rpx rgba(0, 123, 255, 0.3);
        }
      }

      // 骨架屏占位符
      .avatar-skeleton {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: #2c2c2e;
        border-radius: 50%;
        animation: shimmer 1.5s infinite;
        z-index: 0;

        .avatar-skeleton-shimmer {
          width: 100%;
          height: 100%;
          background: inherit;
          border-radius: 50%;
        }
      }
    }

    // 好友内容
    .friend-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      min-width: 0;
      height: 100%;
      margin-right: 20rpx;

      .friend-title-row {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-bottom: 0;
        height: 100%;

        .friend-name {
          flex: 1;
          font-size: 32rpx;
          color: #fff;
          font-weight: 600;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          line-height: 1.2;
        }
      }
    }

    // 右侧操作按钮
    .friend-actions {
      display: flex;
      align-items: center;
      margin-left: 20rpx;
      gap: 12rpx;

      .action-btn {
        padding: 12rpx 20rpx;
        border-radius: 25rpx;
        font-size: 26rpx;
        font-weight: 500;
        border: 1px solid #fff;
        color: #fff;
        white-space: nowrap;
        transition: all 0.3s ease;
        cursor: pointer;
        min-width: 80rpx;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;

        &:active {
          transform: scale(0.95);
        }

        &.reject-btn {
          background-color: transparent;
          border-color: rgba(255, 255, 255, 0.6);
          color: rgba(255, 255, 255, 0.8);

          &:active {
            background-color: rgba(255, 255, 255, 0.1);
            border-color: rgba(255, 255, 255, 0.8);
          }

          &.disabled {
            background-color: rgba(255, 255, 255, 0.1);
            border-color: rgba(255, 255, 255, 0.3);
            color: rgba(255, 255, 255, 0.5);
            cursor: not-allowed;

            &:active {
              transform: none;
              background-color: rgba(255, 255, 255, 0.1);
            }
          }
        }

        &.accept-btn {
          background-color: #007bff;
          border-color: #007bff;
          color: #fff;
          box-shadow: 0 2rpx 8rpx rgba(0, 123, 255, 0.3);

          &:active {
            background-color: #0056b3;
            border-color: #0056b3;
            box-shadow: 0 1rpx 4rpx rgba(0, 123, 255, 0.4);
          }

          &.disabled {
            background-color: rgba(0, 123, 255, 0.5);
            border-color: rgba(0, 123, 255, 0.5);
            color: rgba(255, 255, 255, 0.7);
            cursor: not-allowed;
            box-shadow: none;

            &:active {
              transform: none;
              background-color: rgba(0, 123, 255, 0.5);
            }
          }
        }

        .action-text {
          font-size: 26rpx;
          font-weight: 500;
          line-height: 1;
        }
      }
    }
  }
}

// 加载更多
.loading-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;

  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid rgba(0, 123, 255, 0.2);
    border-top: 4rpx solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.5);
  }
}

// 无数据状态
.empty-friend {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .empty-img {
    width: 180rpx;
    height: 120rpx;
    margin-bottom: 40rpx;
    opacity: 0.5;
  }

  .empty-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.5);
    text-align: center;
  }
}

// 动画
@keyframes spin {
  0% {
    transform: rotate(0deg);
    opacity: 0.8;
  }

  50% {
    opacity: 1;
  }

  100% {
    transform: rotate(360deg);
    opacity: 0.8;
  }
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }

  100% {
    background-position: 200% 0;
  }
}

// 适配不同平台
/* #ifdef APP-PLUS */
.friend-item {
  padding: 20rpx 0;
  min-height: 84rpx;
}

.friend-avatar-wrapper {
  width: 84rpx;
  height: 84rpx;
}

.main-scroll-view {
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain;
}

/* #endif */

/* #ifdef MP-WEIXIN */
.friend-item {
  padding: 20rpx 0;
  min-height: 84rpx;
}

.friend-avatar-wrapper {
  width: 84rpx;
  height: 84rpx;
}

/* #endif */

/* #ifdef H5 */
.friend-item {
  padding: 20rpx 0;
  min-height: 84rpx;
}

.friend-avatar-wrapper {
  width: 84rpx;
  height: 84rpx;
}

/* #endif */
</style>
